import React from 'react';
import menuRoute from "routes/menuRoute";
import { connect } from 'react-redux'
import { messages, deepFullCopy } from "share/common";
import { Card, Table, Row, Col, Popover, Badge, Button, message, Icon } from "antd"

import Condition from 'components/condition'
const { If } = Condition;

import CCService from "containers/setting/cost-center/cost-center.service";
import taxCodeServer from 'containers/finance-setting/tax-code/tax-code-server';
import 'styles/finance-setting/tax-code/tax-code/invoice-type/invoice-type-rule.scss'

class InvoiceTypeRule extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      enableLoading: false,
      disableLoading: false,
      columns: [
        {title: messages('common.sequence')/*序号*/, dataIndex: 'index', width: "5%",
          render: (value, record, index) => this.state.pageSize * this.state.page + index + 1},
        {title: messages('finance-setting.key202')/*值编码*/, dataIndex: 'code'},
        {title: messages('finance-setting.key203')/*值名称*/, dataIndex: 'messageKey',
          render: value => value ? <Popover content={value}>{value}</Popover> : '-'},
        {title: messages('finance-setting.key204')/*值列表状态*/, dataIndex: 'status', width: '10%',
          render: value => <Badge status={value ? 'success' : 'error'}
                                  text={value ? messages('common.enabled') : messages('common.disabled')}/>},
        {title: messages('common.remark')/*备注*/, dataIndex: 'remark',
          render: value => value ? <Popover content={value}>{value}</Popover> : '-'},
        {title: messages('common.column.status')/*状态*/, dataIndex: 'enabled', width: '10%',
          render: value => <Badge status={value ? 'success' : 'error'}
                                  text={value ? messages('common.enabled') : messages('common.disabled')}/>},
      ],
      data: [],
      page: 0,
      pageSize: 10,
      pagination: {
        total: 0
      },
      invoiceTypeInfo: this.props.location.state ? this.props.location.state.invoiceTypeInfo : {},//费用类型编码规则信息
      selectedRowKeys: [],//选中的行，用于启用或者禁用
      dataAll: false,//是否全选的标志
      reverseSelectionMap: {},//当全选的时候，记住这些没勾选的,每一页一个key
    }
  }

  componentDidMount() {
    this.getList()
  }

  getList = () => {
    const { audRuleExpTypeId } = this.props.params;
    const { page, pageSize, dataAll, reverseSelectionMap } = this.state;
    let params = {
      page,
      size: pageSize,
      ruleId: audRuleExpTypeId
    };
    this.setState({ loading: true });
    taxCodeServer.getInvoiceTypeList(params).then(res => {
      let ids = [];
      let data = res.data.rows || [];
      data.map(item => ids.push(item.receiptTypeId));
      this.setState({
        loading: false,
        data,
        pagination: {
          total: res.data.total || 0,
          onChange: this.onChangePager,
          current: page + 1
        }
      }, () => {
        if (dataAll) { //如果有全选全部,翻页就立即勾选,并且需要排除掉没有勾选的
          let currentPageUnselected = reverseSelectionMap[page];
          let currentPageSelected = CCService.getSelected(ids, currentPageUnselected);
          this.onSelectChange(currentPageSelected);
        }
      })
    })
  };

  //分页
  onChangePager = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({ page: page - 1 }, this.getList)
    }
  };

  //修改选中行
  onSelectChange = (selectedRowKeys) => {
    let { dataAll, reverseSelectionMap, data, page } = this.state;
    this.setState({ selectedRowKeys });
    if (dataAll) {
      //如果有全选标志，需要记住没选的
      let allKeys = data.map(item => { return item.receiptTypeId });
      reverseSelectionMap[page] = CCService.getUnSelected(deepFullCopy(allKeys), deepFullCopy(selectedRowKeys));
      this.setState({ reverseSelectionMap })
    } else {
      //不需要记住
      this.setState({ reverseSelectionMap: {} })
    }
  };

  //选择全部
  handleAllSelect = (selectedRowKeys) => {
    this.setState({
      dataAll: true,
      reverseSelectionMap: {},//点击一次全选全部就返回
      selectedRowKeys: [...selectedRowKeys]
    })
  };

  //选择当页
  handleCurrentPageSelect = (selectedRowKeys) => {
    this.onSelectChange(selectedRowKeys);
    this.setState({
      dataAll: false,
      selectedRowKeys: [...selectedRowKeys]
    })
  };

  //取消选择
  handleCancelSelect = () => {
    this.setState({
      dataAll: false,
      selectedRowKeys: []
    })
  };

  //修改状态
  handleChangeStatus = (enable) => {
    const { audRuleExpTypeId } = this.props.params;
    const { selectedRowKeys, reverseSelectionMap, data, dataAll } = this.state;
    let params;
    //全选模式
    if (dataAll) {
      params = {
        audRuleExpTypeId: audRuleExpTypeId,
        excludeIds: CCService.getReverseSelection(deepFullCopy(reverseSelectionMap)),
        enable,
        modelEnum: "ALL_PAGE",
      }
    } else {
      params = {
        audRuleExpTypeId: audRuleExpTypeId,
        currentPageIds: selectedRowKeys,
        enable,
        modelEnum: null,
      }
    }
    this.setState({ enableLoading: enable, disableLoading: !enable, loading: true });
    taxCodeServer.modifyInvoiceTypeEnabled(params).then(() => {
      data.map(item => {
        if (~selectedRowKeys.indexOf(item.receiptTypeId)) {
          item.enabled = enable;
        }
      });
      this.setState({
        loading: false,
        enableLoading: false,
        disableLoading: false,
        selectedRowKeys: [],
        data
      });
      message.success(messages('common.operate.success')/*操作成功*/);
    }).catch(() => {
      this.setState({ enableLoading: false, disableLoading: false })
    })
  };

  //渲染基本信息
  renderBasicInfo = () => {
    const { invoiceTypeInfo } = this.state;
    let renderItem = (label, value) => (
      <Col span={6} className="basic-info-item">
        <span>{label}</span>
        <br/>
        {value}
      </Col>
    );
    return (
      <Card title={messages('common.baseInfo')/*基本信息*/}>
        <Row>
          {renderItem(messages('finance-setting.key132'/*费用类别*/), invoiceTypeInfo.expTypeName)}
          {renderItem(messages('finance-setting.key72'/*规则名称*/), invoiceTypeInfo.ruleName)}
          {renderItem(messages('finance-setting.key133'/*账套名称*/), invoiceTypeInfo.setOfBooksName)}
          {renderItem(messages('common.column.status')/*状态*/, (
            <Badge status={invoiceTypeInfo.enable ? 'success' : 'error'}
                   text={invoiceTypeInfo.enable ? messages("common.status.enable") : messages("common.status.disable")}/>
          ))}
        </Row>
      </Card>
    )
  };

  handleBack = () => {
    const { ruleId } = this.props.params;
    this.context.router.push({
      pathname: menuRoute.getRouteItem('invoice-type').url.replace(':ruleId', ruleId)
    })
  };

  render() {
    const { tenantMode } = this.props;
    const { loading, enableLoading, disableLoading, columns, data, pagination, selectedRowKeys, dataAll } = this.state;
    let rowSelection = {
      selectedRowKeys: selectedRowKeys,
      hideDefaultSelections: true,//去掉默认的
      onChange: this.onSelectChange,
      selections: [
        {
          key: 'ALL_PAGE',
          text: messages('finance-setting.key130'/*全选全部*/),
          onSelect: this.handleAllSelect
        },
        {
          key: 'CURRENT_PAGE',
          text: messages('finance-setting.key131'/*全选当页*/),
          onSelect: this.handleCurrentPageSelect
        },
        {
          key: 'cancel-all',
          text: messages("common.cancel"/*取消*/),
          onSelect: this.handleCancelSelect
        },
      ]
    };
    let buttonDisabled = true;
    if ((selectedRowKeys.length > 0 || dataAll) && !loading) {
      buttonDisabled = false;
    }
    return (
      <div className="invoice-type-rule">
        {this.renderBasicInfo()}
        <If value={tenantMode}>
          <Button loading={enableLoading}
                  className="enabled-button"
                  disabled={buttonDisabled}
                  onClick={() => this.handleChangeStatus(true)}>{messages('common.status.enable')/*启用*/}</Button>
          <Button loading={disableLoading}
                  disabled={buttonDisabled}
                  onClick={() => this.handleChangeStatus(false)}>{messages('common.status.disable')/*禁用*/}</Button>
        </If>
        <div className="table-header">
          <div className="table-header-title">{messages('common.total', {total: pagination.total})}</div>
        </div>
        <Table rowKey="receiptTypeId"
               rowSelection={tenantMode ? rowSelection : undefined}
               columns={columns}
               dataSource={data}
               pagination={pagination}
               loading={loading}
               size="middle"
               bordered
        />
        <a className="button-back" onClick={this.handleBack}>
          <Icon type="rollback" className="button-back-icon"/>{messages('common.back')}
        </a>
      </div>
    )
  }
}

InvoiceTypeRule.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(InvoiceTypeRule)
